<template>
  <div v-loading="pageLoading" class="gl_contentBox gl_heightFull">
    <!-- 控制按钮 -->
    <div class="gl_mb_15 gl_clear">
      <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="clickAdd">新增系统版本</el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="tableLoading" :data="tableData" size="small" class="gl_table_noBorder gl_mb_15" style="width: 100%">
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="系统版本" prop="name" />
      <el-table-column label="售价" prop="genderName">
        <template slot-scope="{ row }">
          <span>{{ formatMoney(row.price) }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="idCardNumber">
        <template slot-scope="{ row }">
          <span>{{ row.creationTime ? row.creationTime.slice(0, 10) : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" prop="time">
        <template slot-scope="{ row }">
          <span>{{ row.validity }} {{ row.validityType ? row.validityType.name : '' }} </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="statusName">
        <template slot-scope="{ row }">
          <span>{{ row.isEnabled ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" :width="180">
        <template slot-scope="{ row }">
          <el-button v-if="!row.isEnabled" size="mini" type="text" @click="clickEnableOrDisable(row, 'ENABLE')">启用</el-button>
          <el-button v-if="row.isEnabled" size="mini" type="text" @click="clickEnableOrDisable(row, 'DISABLE')">禁用</el-button>
          <el-button size="mini" type="text" @click="clickEidt(row)">编辑</el-button>
          <el-button size="mini" type="text" @click="clickDelete(row)"><span class="gl_color_error">删除</span></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="dialogMode === 'NEW' ? '新增系统版本' : '编辑系统版本'"
      class="gl_dialog_TitleLine gl_dl_footer"
      :visible.sync="dialogVisible"
      width="1000px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <div class="gl_px_20">
        <el-form ref="form" class="gl_form_mini" size="medium" :model="vo" :rules="rules" label-position="top" label-width="80px">
          <el-row :gutter="40">
            <el-col :span="12">
              <el-form-item label="系统版本名称" prop="name">
                <el-input v-model="vo.name" style="width: 80%;" maxlength="10" placeholder="请输入系统版本名称" />
              </el-form-item>
              <el-form-item label="系统售价（元）" prop="price">
                <el-input-number v-model="vo.price" style="width: 80%;" placeholder="请输入系统售价（元）" :controls="false" :precision="2" :min="0" :max="21474836" />
              </el-form-item>
              <el-form-item label="默认有效期" prop="validity">
                <el-input-number v-model="vo.validity" style="width: 80%; margin-right: 5%" placeholder="请输入该版本的有效期" :controls="false" :precision="0" :min="0" :max="21474836" />
                <el-select v-model="vo.validityTypeCode" style="width: 15%;" placeholder="请选择">
                  <el-option v-for="item in validityTypeList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
              <el-form-item label="版本介绍" prop="description">
                <el-input
                  v-model="vo.description"
                  type="textarea"
                  style="width: 80%;"
                  :rows="3"
                  maxlength="100"
                  show-word-limit
                  placeholder="请输入版本介绍"
                />
              </el-form-item>

              <el-form-item label="状态" prop="isEnabled">
                <el-radio-group v-model="vo.isEnabled">
                  <el-radio :label="true">启用</el-radio>
                  <el-radio :label="false">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="系统功能模块" prop="moduleIds">
                <div class="checkbox_wrap">
                  <el-checkbox-group v-model="vo.moduleIds">
                    <el-checkbox v-for="(item, index) in modulesList" :key="index" style="width: 40%" :label="item.id">
                      {{ item.name }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="submitLoading" size="mini" @click="submitDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { CopyData } from '@/lib';

import {
  api_GET_Edition, // 获取版本
  api_POST_Edition, // 新增版本
  api_PUT_EditionId, // 编辑版本
  api_DELETE_EditionId, // 删除版本
  api_GET_EditionModules, // 获取所有模块列表
  api_GET_EditionIdModules, // 查询版本模块列表
  api_GET_EditionValidityTypes // 获取有效期类型列表
} from '@/extend/api/swaggerApi/identity.js';

import {
  CreateEditionInput // 版本vo
} from '@/lib/form/swaggerForm.js';

import {
  CreateEditionInput_Rules
} from '@/lib/validate/configuration/index.js';

export default {
  data () {
    const _vo = new CreateEditionInput();
    _vo.validityTypeCode = 'Week'; // 默认给个最小单位
    return {
      pageLoading: false,
      tableLoading: false,
      tableData: [],
      // ---
      dialogMode: '', // NEW 新增 | EDIT 编辑
      dialogVisible: false,
      submitLoading: false,
      vo: _vo,
      rules: new CreateEditionInput_Rules(),
      currentRow: {}, // 点击编辑时，选择的row
      // ---
      validityTypeList: [], // 有效类型字典列表
      modulesList: [] // 全部模块列表 数组
    };
  },
  created () {
    // 获取有效周期类型字典
    this.getValidityType();
    // 获取功能模块列表
    this.getModuleList();
    // 获取页面数据
    this.getPageList();
  },
  methods: {
    // 获取所有模块列表
    getModuleList () {
      api_GET_EditionModules()
        .then(
          res => {
            const _list = res || [];
            _list.sort((a, b) => a.sortOrder - b.sortOrder);
            this.modulesList = _list;
          }
        )
        .catch(
          error => {
            this.$message({
              message: `模块列表获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取有效期类型列表字典
    getValidityType () {
      api_GET_EditionValidityTypes()
        .then(
          res => {
            const _list = res || [];
            _list.sort((a, b) => a.sortOrder - b.sortOrder);
            this.validityTypeList = _list;
          }
        )
        .catch(
          error => {
            this.$message({
              message: `有效期类型获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 获取页面列表
    getPageList () {
      this.apiGetSysVersion({
        // IsEnabled: null, // true | false
        IncludeValidityType: true // true | false
      });
    },
    // 页面列表API
    apiGetSysVersion (_qo) {
      this.tableLoading = true;
      api_GET_Edition(_qo)
        .then(
          res => {
            this.tableLoading = false;
            let _list = res || [];
            _list = _list.filter(item => !item.isDeleted);
            this.tableData = _list;
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            console.log(error);
          }
        );
    },
    // 查询版本模块列表
    apiGetSysVersionModulesById (id) {
      return new Promise((reslove, reject) => {
        api_GET_EditionIdModules(id)
          .then(
            res => {
              reslove(res);
            }
          )
          .catch(
            error => {
              this.$message({
                message: `版本模块列表获取失败 ${error.error.message}`,
                type: 'error',
                showClose: true
              });
              reject(false);
            }
          );
      });
    },
    // 点击新增系统版本
    clickAdd () {
      this.dialogMode = 'NEW';
      this.dialogVisible = true;
    },
    // 点击编辑系统版本
    clickEidt (row) {
      this.currentRow = row;
      this.dialogMode = 'EDIT';
      const _vo = new CreateEditionInput();
      CopyData(row, _vo);
      _vo.price = this.formatMoney(_vo.price);
      this.tableLoading = true;
      this.apiGetSysVersionModulesById(row.id)
        .then(
          res => {
            this.tableLoading = false;
            _vo.moduleIds = res.map(item => item.id);
            this.vo = _vo;
            this.dialogVisible = true;
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            console.log('clickEidt error: ', error);
          }
        );
    },
    // 关闭弹窗
    closeDialog () {
      const _vo = new CreateEditionInput();
      _vo.validityTypeCode = 'Week'; // 默认给个最小单位
      this.vo = _vo;
      this.$nextTick(_ => {
        this.$refs.form.clearValidate();
        this.dialogVisible = false;
      });
    },
    // 确认提交弹窗
    submitDialog () {
      this.$refs.form.validate(
        valid => {
          if (valid) {
            const _vo = JSON.parse(JSON.stringify(this.vo));
            _vo.price = this.yuanToFen(_vo.price);
            if (this.dialogMode === 'NEW') {
              this.apiAddSysVersion(_vo);
            }
            if (this.dialogMode === 'EDIT') {
              this.apiEditSysVersion(this.currentRow.id, _vo);
            }
          }
        }
      );
    },
    apiAddSysVersion (_vo) {
      this.submitLoading = true;
      api_POST_Edition(_vo)
        .then(
          res => {
            this.tableLoading = false;
            this.submitLoading = false;
            this.getPageList();
            this.closeDialog();
            this.$message({
              message: `新增成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.submitLoading = false;
            this.$message({
              message: `新增失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 编辑系统版本API
    apiEditSysVersion (id, vo) {
      this.submitLoading = true;
      api_PUT_EditionId(id, vo)
        .then(
          res => {
            this.tableLoading = false;
            this.submitLoading = false;
            this.getPageList();
            this.closeDialog();
            this.$message({
              message: `编辑成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.submitLoading = false;
            this.$message({
              message: `编辑失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    clickEnableOrDisable(row, type) {
      this.currentRow = row;
      this.tableLoading = true;
      const _vo = new CreateEditionInput();
      CopyData(row, _vo);
      this.apiGetSysVersionModulesById(row.id)
        .then(
          res => {
            _vo.moduleIds = res.map(item => item.id);
            let _actionName;
            if (type === 'ENABLE') {
              _actionName = '启用';
              _vo.isEnabled = true;
            }
            if (type === 'DISABLE') {
              _actionName = '禁用';
              _vo.isEnabled = false;
            }
            this.updateEditionApi(row.id, _vo, { actionName: _actionName });
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            console.log('clickEnableOrDisable error: ', error);
          }
        );
    },
    // 编辑版本API.用于启用禁用
    updateEditionApi (id, vo, params) {
      api_PUT_EditionId(id, vo)
        .then(
          res => {
            this.tableLoading = false;
            this.getPageList();
            this.$message({
              message: `${params.actionName}成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            console.log(error);
            this.$message({
              message: `${params.actionName}失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 点击删除按钮
    clickDelete (row) {
      this.currentRow = row;
      this.$confirm(`您确认是否要删除【${row.name}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            this.apiDelSysVersion(row.id);
          }
        );
    },
    // 删除系统版本API
    apiDelSysVersion (id) {
      this.tableLoading = true;
      api_DELETE_EditionId(id)
        .then(
          res => {
            this.tableLoading = false;
            this.getPageList();
            this.$message({
              message: `删除成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              message: `删除失败 ${error.error.message}`,
              type: 'success',
              showClose: true
            });
          }
        );
    },
    // 格式化货币格式 （分）
    formatMoney (num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 将元转化为分
    yuanToFen(moneyStr) {
      const _moneyStr = String(moneyStr);
      const yuan = Number(_moneyStr.split('.')[0]) || 0;
      const fen = Number(_moneyStr.split('.')[1]) || 0;
      return yuan * 100 + fen;
    }
  }
};
</script>

<style>
  .el-input-number .el-input__inner {
    text-align: left;
  }
</style>
<style lang="scss" scoped>
  .checkbox_wrap {
    box-sizing: border-box;
    height: 100%;
    min-height: 339px;
    padding: 10px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
  }
</style>
